/**
 * author:Administrator
 * date:2016/3/2
 * desc:TODO
 */
"use strict";

let Router = require('koa-router');
let roleService = require('../../ddd/application/roleService.js');
let config = require('../../config/index.js');
let appUtil = require('../../common/appUtils.js');

let bodyParser = require('koa-better-body');
let koabody = bodyParser();
//
let __pathPrefix = '/api/v1/auth';
appUtil.appLog('router:' + __pathPrefix + ',file=' + __filename);
let router = new Router({prefix: __pathPrefix});
module.exports = router.routes();


router.post('/register', koabody, function*() {
  let name = this.request.body.fields.name;
  let pwd = this.request.body.fields.pwd;
  let userType = this.request.body.fields.userType;
  let result;
  if (userType == 'customer') {
    result = yield roleService.registerCustomer(name, pwd);
  } else if (userType == 'vendor') {
    result = yield roleService.registerVendor(name, pwd);
  } else if (userType == 'manager') {
    result = yield roleService.registerManager(name, pwd);
  }
  if (result) return this.body = result;
  else {
    this.status = 401;
    return this.body = 'register fail';
  }
});

router.post('/login', koabody, function*() {
  let name = this.request.body.fields.name;
  let pwd = this.request.body.fields.pwd;
  //let userType = this.request.body.fields.userType;

  let role = yield roleService.login(name, pwd);
  if (!role) {
    this.status = 401;
    this.body = 'wrong name/pwd';
    return;
  }

  console.log(role);
  /**
   * 允许多个身份
   */
  if (role.userType == 'customer') {
    this.session.customer = role;
  } else if (role.userType == 'vendor') {
    this.session.vendor = role;
  } else if (role.userType == 'manager') {
    this.session.manager = role;
  }
  //this.session.role = role;
  this.body = role;
});
